package com.xjoyt.pay.master.services;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.commons.ObjectUtils;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.params.DistributorOrderGroupParam;
import com.xjoyt.pay.master.po.Distributor;
import com.xjoyt.pay.master.repository.DistributorRepository;
import com.xjoyt.pay.master.vo.DistributorOrderGroup;
import com.xjoyt.pay.merchant.register.params.DistributorPageParam;

@Service
public class DistributorOrderService extends AbstractService {

	@Autowired
	private DistributorRepository repository;

	public PageResult<DistributorOrderGroup> loadPageGroup(PageParam<DistributorOrderGroupParam> param) {

		PageParam<DistributorPageParam> p = new PageParam<>();
		ObjectUtils.fieldCopy(param, p);
		PageResult<Distributor> page = repository.loadPage(p);

		List<String> distributorIds = new ArrayList<>();
		List<DistributorOrderGroup> list = new ArrayList<>();

		for (Distributor item : page) {
			distributorIds.add(item.id);
			DistributorOrderGroup vo = new DistributorOrderGroup();
			list.add(vo);
			ObjectUtils.fieldCopy(item, vo);
		}

		if (CollectionUtils.isNotEmpty(distributorIds) && param.query != null) {

			List<Map<String, Object>> sumList = repository.sum(distributorIds, param.query);

			for (Map<String, Object> map : sumList) {
				if (map == null || !map.containsKey("id") || map.get("id") == null)
					continue;
				Object distributorId = map.get("id");
				for (DistributorOrderGroup item : list) {
					if (distributorId.equals(item.id)) {
						item.moneySum = (map.containsKey("sum") && map.get("sum") != null)
								? Double.valueOf(map.get("sum").toString()) : 0D;
						item.numberOfOrders = (map.containsKey("count") && map.get("count") != null)
								? (long) map.get("count") : 0L;
						break;
					}
				}
			}

		}

		return new PageResult<>(page.getTotal(), list);
	}

}
